<?php

namespace App\Traits\User;

use App\Extension\TreeGenerator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

trait HasMenus
{
    /**
     * 获取菜单信息
     *
     * Date: 2018/1/26
     * @author George
     * @return Collection
     */
    protected function getMenusByPermissions(): Collection
    {
        $menus = [];
        //获取用户的角色权限和个人权限
        $permissions = $this->permissions;
        //验证返回
        if ($permissions instanceof Collection && $permissions->isNotEmpty()) {
            foreach ($permissions as $permission) {
                if ($permission->permissiontable_type === 'menu') {
                    $menus[] = Cache::remember("menus:{$permission->permissiontable_id}", 10,function () use ($permission) {
                        return DB::table('menus')
                            ->select(['id', 'parent_id', 'name', 'icon', 'path', 'component', 'meta'])
                            ->where('id', $permission->permissiontable_id)
                            ->first();
                    });
                }
            }
        }

        $menus = $this->regroup($menus);

        return $this->attributes['menus'] = collect($menus);
    }

    /**
     * 定义菜单属性访问器
     *
     * Date: 2018/1/26
     * @author George
     * @return Collection
     */
    public function getMenusAttribute()
    {
        $menus = $this->getMenusByPermissions();
        return $this->attributes['menus'] = $menus;
    }

    protected function regroup($menus)
    {
        if (is_array($menus) && count($menus)) {
        	$tree = new TreeGenerator($menus, 'id', 'parent_id', '0');
        	return $tree->tree;
        }
    }
}
